var express = require('express');
var router = express.Router();

// 导入moment
const moment = require('moment')
const AccountModel = require('../../models/AccountModel');

// 声明中间件
const checkTokenMiddleware = require('../../middlewares/checkTokenMiddleware')


// 记账本的列表
router.get('/account', checkTokenMiddleware, function(req, res, next) {
    console.log(req.user);
    // 获取所有账单数据
    AccountModel.find().sort({time: -1}).then(data => {
      // console.log(data);
      // res.render('list', {accounts: data, moment: moment})
        res.json({
          // 相应编号
          code: '0000',
          msg: '读取成功',
          // 响应数据
          data: data
        })
      }).catch(err => {
        res.json({
          code: 1001,
          msg: '读取失败',
          data: null
        })
      })
    
  
});


// 新增记录
router.post('/account', checkTokenMiddleware, (req, res) => {
  // console.log(req.body);
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  }).then(data => {
    res.json({
      code: '0000',
      msg: '新增成功',
      data: data
    })
  }).catch(err => {
    res.json({
      code: '1002',
      msg: '新增失败',
      data: null
    })
  })
  
})
 
// 删除记录
router.delete('/account/:id', checkTokenMiddleware, (req, res) => {
  const id = req.params.id
  AccountModel.deleteOne({_id: id}).then(data => {
    console.log(data);
    res.json({
      code: '0000',
      msg: '删除成功',
      data: null
    })
  }).catch(err => {
    res.json({
      code: 1003,
      msg: '删除失败',
      data: null
    })
  })
})

// 获取单个账单信息
router.get('/account/:id', checkTokenMiddleware, (req, res) => {
  const id = req.params.id
  console.log(id);
  AccountModel.findById(id).then(data => {
    console.log(data);
    res.json({
      code: '0000',
      msg: '获取成功',
      data: data
    })
  }).catch(err => {
    res.json({
      code: '1004',
      msg: '获取失败',
      data: null
    })
  })
})

// 更新单个账单信息
router.patch('/account/:id', checkTokenMiddleware, async (req, res) => {
  const id = req.params.id
  try {
    const result = await AccountModel.updateOne({_id: id}, req.body)
  } catch (error) {
    res.json({
      code: '1005',
      msg: '更新失败',
      data: null
    })
  }
  
 try {
  const data = await AccountModel.findById(id)
  res.json({
    code: '0000',
    msg: '更新成功',
    data: data
  })
 } catch (error) {
  res.json({
      code: '1004',
      msg: '读取失败',
      data: null
    })
 }
 
 
})

module.exports = router;
